(function (window, gadgets, _IG_Prefs) {
  "use strict";
  window.Config = {
    root: null,
    raw: {},
    folderId: null,
    getUserPref: (function () {
      if (typeof _IG_Prefs === "undefined") {
        return function (key) {
          return this[key];
        };
      }

      var pref = new _IG_Prefs();
      return function (key) {
        return pref.getString(key);
      };
    })(),

    getConfigFolderId: function () {
      return this.folderId;
    },

    getStaticFile: function () {
      var base = ['https://googledrive.com/host', this.folderId];
      for (var i = 0; i < arguments.length; i++) {
        base.push(arguments[i]);
      }

      return base.join("/");
    },

    load: function (successHandler, errorHandler) {
      var _this = this;
      var params = {};
      if (typeof gadgets !== 'undefined' && document.location.host.match(
        /opensocial.googleusercontent.com/)) {
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType
          .JSON;
        params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
        gadgets.io.makeRequest(this.getStaticFile('config.json'), function (
          data) {
          if (!data.data) {
            if (errorHandler) {
              errorHandler();
            }
            return;
          }

          _this.raw = data.data;
          if (successHandler) {
            successHandler(data.data);
          }
        }, params);
      } else {
        $.ajax({
          url: this.getStaticFile('config.json'),
          dataType: 'json',
          success: function (data) {
            _this.raw = data;
            if (successHandler) {
              successHandler(data);
            }
          },
          error: function (e, status) {
            if (status + '' === '404' || status === 'error') {
              if (errorHandler) {
                errorHandler();
              }
            }
          }
        });
      }
    }
  };

  $('script').each(function () {
    var link = $(this).attr('src');
    if (link && link.match(/chronopost\.config\.js$/)) {
      var parts = link.split(/\//);
      parts.splice(parts.length - 1, 1);
      window.Config.root = parts.join('/');
      var grep = /host\/(.+?)\//i;
      var match = link.match(grep) || document.location.href.match(grep);
      window.Config.folderId = match[1];
      console.log("Root url: " + window.Config.root);
      console.log("Folder id: " + window.Config.folderId);
    }
  });
})(this, this.gadgets, this._IG_Prefs);
